import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {Button, Modal, Row,Col,Steps,Card,Badge,Collapse,Tabs, BackTop} from 'antd';
import DescriptionList from 'components/DescriptionList';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './TestRecordDetail.less';

import RecordInfo from './RecordInfo';
import RecordStep from './RecordStep';
import TestRecordForm from './TestRecordForm';
import RecordHistory from './RecordHistory';

const { TabPane } = Tabs;
const { Step } = Steps;
const { Description } = DescriptionList;
const ButtonGroup = Button.Group;



@connect(({ testrecord, project, user, version, loading }) => ({
  version: version.currentVersion,
  users: testrecord.users,
  historyRecordList: testrecord.historyRecordList,
  testStatusList: testrecord.testStatusList,
  formModalVisible: testrecord.formModalVisible,
  activeRecord: testrecord.activeRecord,
  currentUser: user.currentUser,
  currentUserOwnedProjectList: project.currentUserOwnedProjectList,
  loading: loading.effects['testrecord/queryVersionRecord'],
}))
export default class TestRecordDetail extends Component {

  componentDidMount() {
    this.props.dispatch({
      type:'testrecord/queryVersionRecord',
      payload: this.props.location.state
    })
    this.props.dispatch({
      type: 'user/fetchCurrent'
    })
    this.props.dispatch({
      type: 'project/queryCurrentUserOwnedProjects',
    })
  }

  handleEdit = (record) => {
    let status = 0;
    let { currentUserOwnedProjectList } = this.props;
    currentUserOwnedProjectList.forEach(
      function(data){
        if(data.id===record.projectId){
          status += 1
        }
      }
    ) 
    //console.log('record..',record)
    if(status===0){
      return Modal.info({
        title: '权限管理',
        content: '非该项目开发人员无法编辑',
        destroyOnClose: true
      });
    }else{
      this.props.dispatch({
        type:'testrecord/showEditForm',
        payload: record
      })
    }
  }

  action = (record, currentUser) => {
    if(!record){
      return null;
    }
    return (
      <Fragment>
        <ButtonGroup>
          <Button onClick={this.handleEdit.bind(this, record)}>编辑</Button>
          <Button>导出</Button>
        </ButtonGroup>
       {currentUser && currentUser.roleId === 2 ?  <Button type="primary" onClick={this.gotoTestPage}>重新提测</Button>:null} 
      </Fragment>
    );
  }

  gotoTestPage = () => {
    this.props.dispatch(routerRedux.push('/testcenter/testsubmit/info'))
  }

  historyRecord = (historyRecord, version) =>{
    if(!historyRecord ){
      return null
    }else{
      historyRecord.sort((a, b) => {
        return a.versionTestCount < b.versionTestCount;
      });
      let list = _.tail(historyRecord).map(r => {
        let {recordInfo, recordLog} = r;
        return <Collapse.Panel header={`第${r.versionTestCount}次提测记录`} key={r.id} >
                <RecordInfo testRecord={recordInfo} version={version} recordLog={recordLog}/>
         </Collapse.Panel>
        // return <RecordHistoryPanel header={`第${r.versionTestCount}次提测记录`} key={r.id} onClick={this.handleHistoryCollapse}></RecordHistoryPanel>
      });
      return list;
    }
  }

  handleHistoryCollapse (params){
    this.props.dispatch({
      type:'testrecord/handleHistoryCollapse',
      payload: {params}
    })
  }

  render() {
    const { historyRecordList, version, users,  currentUser, testStatusList} = this.props;

    const lastRecord = historyRecordList && historyRecordList.length > 0 ? historyRecordList[0] : undefined;

    const testrecordID = lastRecord ? `${lastRecord.projectName}-${lastRecord.versionName}-ID${lastRecord.id}`:'';
    const historyRecordCount = historyRecordList ? historyRecordList.length : 0;

    

    return (
      <PageHeaderLayout
        title={`提测ID：${testrecordID}`}
        logo={<img alt="" src="../src/assets/mBlock1.png" />}
        action={this.action(lastRecord, currentUser)}
        content={description(lastRecord, version)}
        extraContent={extra(lastRecord, version,  testStatusList)}
      >
        <Card>
          <Tabs style={{ overflow: 'visible' }}>
            <TabPane tab="当前提测详情" key="detail">
                { lastRecord && users ? <RecordStep  testRecord={lastRecord} version={version}  users={users} /> : null}
                { lastRecord && version ? <RecordInfo testRecord={lastRecord} version={version}  /> : null }
            </TabPane>
            <TabPane tab={<Badge>历史提测记录&nbsp;&nbsp;&nbsp;</Badge>} key="record">
              <BackTop />
              { historyRecordList ? <RecordHistory historyRecordList={historyRecordList} version={version} handleHistoryCollapse={this.handleHistoryCollapse.bind(this)}/> : null}
            </TabPane>
          </Tabs>
        </Card>
        <TestRecordForm 
          visible={this.props.formModalVisible}
          data = {this.props.activeRecord}
          />
      </PageHeaderLayout>
    );
  }
}


const description = (lastRecord, version) => {
  let testCreator = lastRecord ? `${lastRecord.createRealName}(${lastRecord.createUserName})` : '';
  
  return (
  <DescriptionList className={styles.headerList} size="small" col="2">
    <Description term="提测人">{testCreator}</Description>
    <Description term="提测项目">{lastRecord ? lastRecord.projectName:''}</Description>
    <Description term="提测时间">{lastRecord ? lastRecord.testCreateTime:''}</Description>
    <Description term="当前提测版本">{lastRecord ? `${lastRecord.versionName}.${lastRecord.versionTestCount}`:''}</Description>
    <Description term="预提测日期">{version ? version.expectTestTime:''}</Description>
    <Description term="版本预发布日期">{version ? version.expectVersionReleaseTime:''}</Description>
  </DescriptionList>
)};

const mapTestStatusText = (testStatusList, value) => {
  let text = testStatusList.filter((ts) => {
    return parseInt(ts.value) === value;
  })[0].text;
  return text;
}

const extra = ( lastRecord, version, testStatusList) => {
  if(!lastRecord){
    return null;
  }
  return (<Row>
    <Col xs={24} sm={12}>
      <div className={styles.textSecondary}>当前状态</div>
      <div className={styles.heading}>{lastRecord ? mapTestStatusText(testStatusList, lastRecord.testStatus):''}</div>
    </Col>
    <Col xs={24} sm={12}>
      <div className={styles.textSecondary}>提测延期天数</div>
      <div className={styles.heading} style={{color:'red'}}>{version ? version.testDelayTime : 0}</div>
    </Col>
    <Col xs={24} sm={12}>
      <div className={styles.textSecondary}>提测次数</div>
      <div className={styles.heading}>{version ? version.recordCount : 0 }</div>
    </Col>
    <Col xs={24} sm={12}>
      <div className={styles.textSecondary} >打回次数</div>
      <div className={styles.heading} style={{color:'red'}}>{version ? version.backRecordCount : 0 }</div>
    </Col>
  </Row>);
}
